<template>
  <div style="background: #f5f7fa; padding: 24px;">
    <!-- 用户信息卡片 -->
    <a-card style="margin-bottom: 24px;">
      <a-row align="middle">
        <a-col :span="4">
          <a-avatar :size="64" :src="loginUser?.userAvatar">
            {{ loginUser?.userName?.charAt(0) }}
          </a-avatar>
        </a-col>
        <a-col :span="20">
          <h2>{{ loginUser?.userName }}</h2>
          <p>账号：{{ loginUser?.userAccount }}</p>
        </a-col>
      </a-row>
    </a-card>

    <!-- 统计卡片 -->
    <a-row gutter="16" style="margin-bottom: 24px;">
      <a-col :span="8">
        <a-card>
          <a-statistic title="我的总分" :value="totalScore" suffix="分" />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <a-statistic title="累计加分" :value="addScore" suffix="分" value-style="color: #52c41a" />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <a-statistic title="累计减分" :value="minusScore" suffix="分" value-style="color: #f5222d" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 折线图 -->
    <div style="background: #fff; padding: 24px; border-radius: 8px; margin-bottom: 24px;">
      <div ref="chartRef" style="width: 100%; height: 300px;"></div>
    </div>

    <!-- 分数记录表格 -->
    <div style="background: #fff; padding: 24px; border-radius: 8px;">
      <h3 style="margin-bottom: 16px;">我的分数记录</h3>
      <a-table :columns="columns" :data-source="dataSource" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.dataIndex === 'operator'">
            {{ record.operator?.userName || '-' }}
          </template>
          <template v-else-if="column.dataIndex === 'score'">
            <span :style="{ color: record.type==='加分' ? '#52c41a' : '#f5222d' }">
              {{ record.type==='加分'? '+' : '-' }}{{ record.score }}
            </span>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { Card, Row, Col, Statistic, Table, message } from 'ant-design-vue'
import { getScoreByPageUsingPost, getUserScoreAnalyzeVoUsingPost } from '@/api/scoreController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import dayjs from 'dayjs'

// 获取当前登录用户信息
const loginUser = useLoginUserStore().loginUser

// 统计卡片数据
const totalScore = ref(0)
const addScore = ref(0)
const minusScore = ref(0)

// 折线图数据
const chartData = ref<{ date: string, score: number }[]>([])

// 表格数据
const columns = [
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '原因', dataIndex: 'reason', key: 'reason' },
  { title: '分数', dataIndex: 'score', key: 'score' },
  { title: '操作员', dataIndex: 'operator', key: 'operator' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
]

const dataSource = ref<API.UserScoreAnalyzeVo[]>([])
const chartRef = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 数据请求与统计
const fetchData = async () => {
  if (!loginUser?.id) {
    message.error('未获取到用户信息')
    return
  }

  // 只获取当前用户的分数数据
  const res = await getUserScoreAnalyzeVoUsingPost({
    current: 1,
    pageSize: 1000,
    userId: loginUser.id,
    sortField: 'createTime',
    sortOrder: 'descend'
  })

  if (!res.data?.records) {
    message.error('获取分数数据失败')
    return
  }

  const records = res.data.records
  dataSource.value = records

  // 统计卡片
  let total = 0, add = 0, minus = 0
  records.forEach(item => {
    if (item.score) {
      total += item.score
      if (item.type === '加分') add += item.score
      if (item.type === '减分') minus += item.score
    }
  })
  totalScore.value = total
  addScore.value = add
  minusScore.value = minus

  // 统计折线图（按日期分组求和）
  const dateMap: Record<string, { add: number, minus: number }> = {}
  records.forEach(item => {
    const date = item.createTime ? item.createTime.slice(0, 10) : '未知'
    if (!dateMap[date]) {
      dateMap[date] = { add: 0, minus: 0 }
    }
    if (item.type === '加分') {
      dateMap[date].add += item.score || 0
    } else if (item.type === '减分') {
      dateMap[date].minus += item.score || 0
    }
  })
  
  // 转换数据格式并排序
  const dates = Object.keys(dateMap).sort()
  const addScores = dates.map(date => dateMap[date].add)
  const minusScores = dates.map(date => dateMap[date].minus)

  // 更新ECharts
  if (chartRef.value) {
    if (!chartInstance) chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption({
      title: {
        text: '我的分数变化趋势',
        left: 'center'
      },
      tooltip: { 
        trigger: 'axis',
        formatter: function(params: any) {
          let result = params[0].axisValue + '<br/>'
          params.forEach((param: any) => {
            const value = param.value
            const sign = param.seriesName === '加分' ? '+' : '-'
            result += `${param.marker} ${param.seriesName}: ${sign}${Math.abs(value)}<br/>`
          })
          return result
        }
      },
      legend: {
        data: ['加分', '减分'],
        top: 30
      },
      xAxis: {
        type: 'category',
        data: dates,
      },
      yAxis: { 
        type: 'value',
        axisLabel: {
          formatter: function(value: number) {
            return value > 0 ? '+' + value : value
          }
        }
      },
      series: [
        {
          name: '加分',
          data: addScores,
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.1
          },
          lineStyle: { 
            color: '#52c41a',
            width: 2
          },
          itemStyle: {
            color: '#52c41a'
          }
        },
        {
          name: '减分',
          data: minusScores,
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.1
          },
          lineStyle: { 
            color: '#f5222d',
            width: 2
          },
          itemStyle: {
            color: '#f5222d'
          }
        }
      ],
    })
  }
}

onMounted(fetchData)
</script>

<style scoped>
.ant-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
</style>
